import {
	API,
	APIs_NOT_AUTH,
	APIs_STATIC_DATA
} from '@/api.js'
import {
	BASE_URL
} from '@/const.js'
import store from 'store'

const debug = false;

function log(msg) {
	if (debug) {
		console.log(msg);
	}
}

var requestCount = 0

function decreaseReq() {
	requestCount -= 1
	// console.log('requestCount=', requestCount)
	if (requestCount == 0) {
		uni.hideLoading()
	}
}

function askLogin() {
	if (store.state.loginPopup) {
		return
	}
	store.commit("setLoginPopup", true)
	uni.showModal({
		title: "您还没有登陆，请先登陆！",
		cancelText: "再看看",
		confirmText: "去登陆",
		success: (res) => {
			store.commit("setLoginPopup", false)
			if (res.confirm) {
				store.commit("navToLogin", 500);
			} else {
				store.commit("finishLogin");
				let pages = getCurrentPages()
				
				if (pages.length > 1) {
					uni.navigateBack()
				} else {
					let p = pages[0]
					if (p && p.route != '/pages/platform/goods-list' && p.route != '/pages/user/user') {
						uni.reLaunch({
							url: '/pages/platform/goods-list'
						})
					}
				}
			}
		}
	})
}

function logout() {
	store.commit('logout');
}

function checkNeedAuth(url) {
	for (var i = 0; i < APIs_NOT_AUTH.length; i++) {
		let t = APIs_NOT_AUTH[i];
		if (url.startsWith(t)) {
			return false;
		}
	}
	return true;
}

export function request(options) {
	console.log("request option", options);
	const isLogin = options.url === API.login || options.url === API.loginWithPwd;
	const isStaticDataUrl = APIs_STATIC_DATA.indexOf(options.url) != -1
	const token = uni.getStorageSync('uni_id_token')
	const baseConfig = {};
	return new Promise((resolve, reject) => {
		if (!options.url) {
			reject('请传入要请求的URL')
		};
		var needAuth = true;
		if (options.needAuth !== undefined) {
			needAuth = options.needAuth;
		}
		if (!token && needAuth) {
			logout();
			askLogin();
			reject('您还没有登陆')
			return
		}
		baseConfig.header = {
			'content-type': options.contentType ? options.contentType : 'application/json',
			'client_id': 'app',
			'client_secret': 'app'
		}
		if (!isLogin && needAuth) {
			baseConfig.header.Authorization = 'bearer ' + token
		}
		if (options.baseUrl) {
			options.url = options.baseUrl + options.url
		} else {
			options.url = BASE_URL + options.url
		}
		options.success = res => {
			// console.log(`response: ${JSON.stringify(res)}`);
			decreaseReq()
			if (res.statusCode !== 401) {
				store.commit("finishLogin");
			}
			if (res.statusCode == 200) {
				if (isStaticDataUrl) {
					return resolve(res.data)
				}
				// 单独处理错误信息
				if (options.errHandle) {
					return resolve(res.data);
				}
				if (res.data.code == 200) {
					// 弹出成功请求
					if (options.succNotice) {
						uni.showToast({
							icon: 'none',
							title: res.data.msg || '请求成功!'
						});
					}
					return resolve(res.data.data);
				}
				uni.showToast({
					icon: 'none',
					duration: 3000,
					title: res.data.msg || '接口数据格式返回异常!'
				});
				// console.log(`调用接口${options.url}遇到错误`, res.data.msg);
				reject(res.data.msg);
				return;
			}
			if (res.statusCode == 401) {
				if (isLogin) {
					uni.showToast({
						icon: "none",
						title: res.data.msg
					})
					return;
				}
				logout();
				askLogin();
				// console.log(`调用接口${options.url}遇到错误`, "未登陆");
				reject('登录已过期!')
				return
			}
			// 网络状态错误的情况
			uni.showToast({
				icon: 'none',
				duration: 3000,
				title: res.statusText || '网络请求错误, 请检查网络'
			});
			// console.log(`调用接口${options.url}遇到错误`, res);
			reject(res.statusText || '网络请求错误, 请检查网络');
		}
		options.fail = err => {
			// 关闭loading
			// console.log(`request error.${JSON.stringify(err)}`);
			decreaseReq()
			uni.showToast({
				icon: 'none',
				duration: 5000,
				title: '请求超时,请检查网络!'
			});
			reject(err.errMsg);
		}
		options.complete = () => {
			// console.log('request completed')
		}
		var showLoading = true;
		if (options.showLoading !== undefined) {
			showLoading = options.showLoading;
		}
		if (showLoading && requestCount == 0) {
			uni.showLoading({
				title: options.loadingText || '加载中',
				mask: true
			});
		}
		// console.log(`request: ${JSON.stringify(options)}`);
		log(`request: ${JSON.stringify(options)}`);
		requestCount += 1
		// console.log('requestCount=', requestCount)
		return uni.request(Object.assign({}, baseConfig, options))
	})
};

export function callFunc(options) {
	var showLoading = true;
	if (options.showLoading !== undefined) {
		showLoading = options.showLoading;
	}
	if (showLoading) {
		uni.showLoading({
			mask: true
		})
	}
	return new Promise((resolve, reject) => {
		uniCloud.callFunction({
			name: options.funcName,
			data: options.data
		}).then(res => {
			if (showLoading) {
				uni.hideLoading();
			}
			if (res.result.code !== 401) {
				store.commit("finishLogin");
			}
			if (res.result.code === 200) {
				resolve(res.result.result);
			} else if (res.result.code === 401 || res.result.code === 'TOKEN_INVALID' || res.result.code === 'TOKEN_INVALID_TOKEN_EXPIRED' || res.result.code === 'TOKEN_INVALID_ANONYMOUS_USER') {
				logout();
				askLogin();
				// console.log(`调用接口${options.url}遇到错误`, "未登陆");
				reject('登录已过期!')
				return
			} else {
				uni.showToast({
					title: res.result.msg,
					icon: "none",
					duration: 2000
				})
				reject(res.result);
			}
		}).catch(e => {
			if (showLoading) {
				uni.hideLoading();
			}
			if (/30205/.test(e.message)) {
				logout();
				askLogin();
			} else {
				uni.showModal({
					content: e.message,
					showCancel: false
				})
			}
			reject(e);
		}).finally(() => {})
	})
}

export function download(options) {
	const token = uni.getStorageSync('token')
	const baseConfig = {};
	return new Promise((resolve, reject) => {
		if (!options.url) {
			reject('请传入要请求的URL')
		};
		if (!token && APIs_NOT_AUTH.indexOf(options.url) == -1) {
			setTimeout(() => {
				uni.navigateTo({
					url: '/pagesFoo/public/login'
				});
			}, 500)
			reject('您还没有登陆')
			return
		}
		if (options.baseUrl) {
			options.url = options.baseUrl + options.url
		} else {
			options.url = BASE_URL + options.url
		}
		options.success = res => {
			// console.log(`response: ${JSON.stringify(res)}`);
			uni.hideLoading();
			if (res.statusCode >= 200 && res.statusCode < 300) {
				resolve(res.tempFilePath);
				return;
			} else if (res.statusCode == 401) {
				uni.showToast({
					icon: 'none',
					title: '登录已过期'
				});
				setTimeout(function() {
					uni.navigateTo({
						url: '/pagesFoo/public/login'
					});
				}, 3000)
				reject('登录已过期!')
				return
			}
			// 网络状态错误的情况
			uni.showToast({
				icon: 'none',
				duration: 3000,
				title: res.statusText || '网络请求错误, 请检查网络'
			});
			reject(res.statusText || '网络请求错误, 请检查网络');
		}
		options.fail = err => {
			// 关闭loading
			// console.log(`request error.${JSON.stringify(err)}`);
			uni.showToast({
				icon: 'none',
				duration: 5000,
				title: '请求超时,请检查网络!'
			});
			reject(err.errMsg);
		}
		options.complete = () => {
			console.log('request completed')
		}
		baseConfig.header = {
			'content-type': options.contentType ? options.contentType : 'application/json',
			'client_id': 'app',
			'client_secret': 'app',
			'Authorization': 'bearer ' + token
		}
		let showLoading = true;
		if (options.showLoading !== undefined) {
			showLoading = options.showLoading;
		}
		if (showLoading && requestCount == 0) {
			uni.showLoading({
				title: options.loadingText || '加载中',
				mask: true
			});
		}
		// console.log(`request: ${JSON.stringify(options)}`);
		return uni.downloadFile(Object.assign({}, baseConfig, options))
	})
}
